//
//  LDCAddPatientViewController.m
//  LaiKeDaoClient
//
//  Created by zouzhisheng on 15/9/28.
//  Copyright © 2015年 LKD. All rights reserved.
//

#import "LDCAddPatientViewController.h"
#import "LDCEditMarkViewController.h"
#import "LDCScanViewController.h"
#import "Scan_VC.h"
@implementation AddPatientNavigationController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.view.backgroundColor = [UIColor clearColor];
    AddPatientNavigationController *addPatientVC=[[AddPatientNavigationController alloc] init];
    self.viewControllers = @[addPatientVC];
    self.title=@"添加患者";
}
@end



@interface LDCAddPatientViewController ()<UITableViewDataSource,UITableViewDelegate>{
    UITableView                     *m_tableView;
    UITextField * recognizerTF;
    UITextField *mobileTF;
    
}

@end

@implementation LDCAddPatientViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNaviLeftButton:@""];
    [self setNaviTitle:@"添加患者"];
    
    self.view.backgroundColor = [UIColor colorWithHexString:@"0xF2F2F2"];
    
    m_tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64) style:UITableViewStylePlain];
    m_tableView.backgroundColor = [UIColor clearColor];
    m_tableView.delegate = self;
    m_tableView.dataSource = self;
    m_tableView.separatorColor = [UIColor clearColor];
    [self.view addSubview:m_tableView];
    
    
    
    
    // Do any additional setup after loading the view.
}
-(void)viewDidDisappear:(BOOL)animated{
   
        [_iflyRecognizerView cancel]; //取消识别
        [_iflyRecognizerView setDelegate:nil];
        [_iflyRecognizerView setParameter:@"" forKey:[IFlySpeechConstant PARAMS]];
        [super viewWillDisappear:animated];

}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden=NO;
}
#pragma mark - tableview delegate
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return 97;
    }
    else if (indexPath.section == 1){
        return 271;
    }
    else{
        return 91;
    }
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString* str=  @"cell";
    static NSString* twostr = @"twocell";
    static NSString* thdstr = @"thdstr";
    if (indexPath.section == 0) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:str];
        if (!cell) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil] objectAtIndex:0];
        }
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        _patientIDTF=(UITextField*)[cell.contentView viewWithTag:10];
        UIButton *saoBt=(UIButton*)[cell.contentView viewWithTag:11];
        [saoBt addTarget:self action:@selector(saomiaoAction:) forControlEvents: UIControlEventTouchUpInside];
        mobileTF=(UITextField*)[cell.contentView viewWithTag:12];
        
        return cell;
    }
    else if (indexPath.section == 1){
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:twostr];
        if (!cell) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil] objectAtIndex:1];
        }
        
        UIButton *tfvoice = (UIButton *)[cell.contentView viewWithTag:10];
        recognizerTF = (UITextField*)[cell.contentView viewWithTag:11];
        UIButton *editbtn = (UIButton*)[cell.contentView viewWithTag:12];
        
        [editbtn addTarget:self action:@selector(editmarkButton:) forControlEvents:UIControlEventTouchUpInside];
        
        tfvoice.layer.borderColor = [UIColor colorWithHexString:@"0x00b1ef"].CGColor;
        tfvoice.layer.borderWidth = 0.5;
        
        recognizerTF.layer.borderColor = [UIColor lightGrayColor].CGColor;
        recognizerTF.layer.borderWidth = 0.5;
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [tfvoice addTarget:self action:@selector(voiceRecogniseAction:) forControlEvents:UIControlEventTouchUpInside];
        

        return cell;
    }
    else{
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:thdstr];
        if (!cell) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil] objectAtIndex:2];
        }
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        UIButton *confirmBt=(UIButton*)[cell.contentView viewWithTag:10];
        [confirmBt addTarget:self action:@selector(confirmAction:) forControlEvents:UIControlEventTouchUpInside];
        return cell;
    }
    
}

-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return nil;
    }
    else if (section == 1){
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 30)];
        view.backgroundColor = [UIColor clearColor];
        
        UILabel *label = [[UILabel alloc] initWithFrame:(CGRect){0,10,SCREEN_HEIGHT,20}];
        label.font = [UIFont systemFontOfSize:14];
        label.textColor = [UIColor blackColor];
        label.text = @"    添加标签";
        [view addSubview:label];
        
        return view;
    }
    return nil;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 10;
    }else if (section == 1){
        return 30;
    }else{
        return 0;
    }
}
//- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
//{
//    return 20;
//}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)clickLeftButton:(UIButton*)sender
{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

-(void)editmarkButton:(UIButton*)sender{
    LDCEditMarkViewController *pv = [LDCEditMarkViewController new];
    [self.navigationController pushViewController:pv animated:YES];
}
#pragma mark-扫一扫
-(void)saomiaoAction:(UIButton*)bt{
    Scan_VC *scanVC=[[Scan_VC alloc] init];
    scanVC.delegate=self;
    [self.navigationController pushViewController:scanVC animated:YES];
    
}
#pragma mark-语音识别
-(void)voiceRecogniseAction:(UIButton*)bt{
    
        recognizerTF.text=@"";
        if(_iflyRecognizerView == nil)
        {
            [self initRecognizer ];
        }
        
        //设置音频来源为麦克风
        [_iflyRecognizerView setParameter:IFLY_AUDIO_SOURCE_MIC forKey:@"audio_source"];
        
        //设置听写结果格式为json
        [_iflyRecognizerView setParameter:@"plain" forKey:[IFlySpeechConstant RESULT_TYPE]];
        
        //保存录音文件，保存在sdk工作路径中，如未设置工作路径，则默认保存在library/cache下
        [_iflyRecognizerView setParameter:@"asr.pcm" forKey:[IFlySpeechConstant ASR_AUDIO_PATH]];
        
        [_iflyRecognizerView start];

    
}
/**
 设置识别参数
 ****/
-(void)initRecognizer
{
    NSLog(@"%s",__func__);
    
        //单例模式，UI的实例
        if (_iflyRecognizerView == nil) {
            //UI显示剧中
            _iflyRecognizerView= [[IFlyRecognizerView alloc] initWithCenter:self.view.center];
            
            [_iflyRecognizerView setParameter:@"" forKey:[IFlySpeechConstant PARAMS]];
            
            //设置听写模式
            [_iflyRecognizerView setParameter:@"iat" forKey:[IFlySpeechConstant IFLY_DOMAIN]];
            
        }
        _iflyRecognizerView.delegate = self;
        
        if (_iflyRecognizerView != nil) {
            IATConfig *instance = [IATConfig sharedInstance];
            //设置最长录音时间
            [_iflyRecognizerView setParameter:instance.speechTimeout forKey:[IFlySpeechConstant SPEECH_TIMEOUT]];
            //设置后端点
            [_iflyRecognizerView setParameter:instance.vadEos forKey:[IFlySpeechConstant VAD_EOS]];
            //设置前端点
            [_iflyRecognizerView setParameter:instance.vadBos forKey:[IFlySpeechConstant VAD_BOS]];
            //网络等待时间
            [_iflyRecognizerView setParameter:@"20000" forKey:[IFlySpeechConstant NET_TIMEOUT]];
            
            //设置采样率，推荐使用16K
            [_iflyRecognizerView setParameter:instance.sampleRate forKey:[IFlySpeechConstant SAMPLE_RATE]];
            if ([instance.language isEqualToString:[IATConfig chinese]]) {
                //设置语言
                [_iflyRecognizerView setParameter:instance.language forKey:[IFlySpeechConstant LANGUAGE]];
                //设置方言
                [_iflyRecognizerView setParameter:instance.accent forKey:[IFlySpeechConstant ACCENT]];
            }else if ([instance.language isEqualToString:[IATConfig english]]) {
                //设置语言
                [_iflyRecognizerView setParameter:instance.language forKey:[IFlySpeechConstant LANGUAGE]];
            }
            //设置是否返回标点符号
            [_iflyRecognizerView setParameter:instance.dot forKey:[IFlySpeechConstant ASR_PTT]];
            
        }
}

- (void)onResult:(NSArray *)resultArray isLast:(BOOL)isLast
{
    NSMutableString *result = [[NSMutableString alloc] init];
    NSDictionary *dic = [resultArray objectAtIndex:0];
    
    for (NSString *key in dic) {
        [result appendFormat:@"%@",key];
    }
    NSLog(@"识别结果===%@",result);
    recognizerTF.text=[NSString stringWithFormat:@"%@%@",recognizerTF.text,result];
}
#pragma mark-添加患者
-(void)confirmAction:(UIButton*)bt{
    __weak typeof(self)weakSelf = self;
    [CSHApiClient addPatientNumAppend_tag:recognizerTF.text Tag_ids:@"" patient_code:_patientIDTF.text tel:mobileTF.text DidFinishLoaded:^(KXJson *json, NSString *path) {
        int code=[json getIntForKey:@"code"];
        if (code==200) {
          [weakSelf dismissViewControllerAnimated:YES completion:^{
              
          }];
        }
        
    } didFailLoaded:^(NSError *error, NSString *path) {
        
    }];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
